import React, { useState } from 'react';
import { connect } from 'dva';
import { useUpdateEffect } from '@umijs/hooks';
import { Tooltip, Row, Col, Card, Form, Input, Button, Modal, message, Divider} from 'antd';
import dynamic from 'umi/dynamic';
import LoadingComponent from '@/components/PageLoading/index';
import request from '@/utils/request';
import SlickTable from '@/components/SlickTable';
import useSlickTableTemp from '@/hooks/useSlickTableTemp';
import moment from 'moment';
import styles from './styles.less';

const namespace = 'componentManage';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 8 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 16 },
  },
};

// 判断空对象
const isEmptyObject = obj => {
  if (Object.keys(obj).length === 0) {
    return true;
  }
  return false;
};

const ComponentAdd = dynamic({
  loader: () => import('./components/ComponentAdd'),
  loading: LoadingComponent,
});

function ComponentManage(props) {
  const { getFieldDecorator } = props.form;
  const [params, setParams] = useState({}); // 查询条件

  // 初始化表格数据
  const { tableProps } = useSlickTableTemp(
    { pageSize: 10 },
    'pmc/pcms/component/queryPage',
    params
  );

  useUpdateEffect(() => {
    if (isEmptyObject(props.selectComponent)) {
      setParams({
        ...params,
      });
    }
  }, [props.selectComponent]);

  // 通过dva存当前需要传递的数据
  const saveSelectComponent = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveSelectComponent`,
      payload: params,
    });
  };

  const saveComponentAddVisibleFlag = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveComponentAddVisibleFlag`,
      payload: params,
    });
  };

  const saveComponentAddType = params => {
    const { dispatch } = props;
    dispatch({
      type: `${namespace}/saveComponentAddType`,
      payload: params,
    });
  };

  // 查询
  const handleQuery = () => {
    const formData = props.form.getFieldsValue();
    formData.pageNum = 1;
    formData.pageSize = 10;
    formData.gb_reset = true;
    setParams(formData);
  };

  // 重置查询条件
  const handleReset = () => {
    props.form.resetFields();
  };

  // 新增组件
  const handleAdd = () => {
    saveComponentAddType('add');
    saveComponentAddVisibleFlag(true);
  };

  // 修改自定义组件
  const handleModify = record => {
    saveSelectComponent(record);
    saveComponentAddType('modify');
    saveComponentAddVisibleFlag(true);
  };

  // 删除自定义组件
  const handleDelete = record => {
    Modal.confirm({
      content: '确定删除选中自定义组件？',
      okText: '确定',
      cancelText: '取消',
      onOk() {
        request('pmc/pcms/component/delete', {
          method: 'GET',
          data: { componentId: record.componentId },
        }).then(res => {
          if (res && res.success === true) {
            message.success('删除成功');
            saveSelectComponent({});
          } else if (res && res.errMessage) {
            message.error(res.errMessage);
          } else {
            message.error('删除失败');
          }
        });
      },
    });
  }

  // const busiComponentAddCallBack = () => {

  // };

  const cellStyle = {
    maxWidth: 200,
    overflow: 'hidden',
    whiteSpace: 'nowrap',
    textOverflow: 'ellipsis',
    cursor: 'pointer',
  };

  const columns = [
    {
      title: '组件名称',
      dataIndex: 'componentName',
      onCell: () => {
        return {
          style: cellStyle,
        };
      },
      render: text => (
        <Tooltip placement="topLeft" title={text}>
          {text}
        </Tooltip>
      ),
    },
    {
      title: '组件编码',
      dataIndex: 'componentCode',
    },
    {
      title: '组件类型',
      dataIndex: 'componentTypeName',
    },
    {
      title: '创建时间',
      dataIndex: 'createDate',
      render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : null),
    },
    {
      title: '修改时间',
      dataIndex: 'updateDate',
      render: text => (text ? moment(text).format('YYYY-MM-DD HH:mm:ss') : null),
    },
    {
      title: '操作',
      render: (text, record) => {
        return (
          <span>
            <a
              onClick={() => {
                handleModify(record);
              }}
            >
              编辑
            </a>
            <Divider type="vertical" />
            <a
              onClick={() => {
                handleDelete(record);
              }}
            >
              删除
            </a>
          </span>
        );
      },
    },
  ];

  return (
    <div>
      <Card
        title="自定义组件管理"
        className="cute"
        style={{ height: '100%' }}
        extra={
          <div>
            <Button
              className="margin-left"
              type="primary"
              onClick={() => {
                handleAdd();
              }}
            >
              新增自定义组件
            </Button>
          </div>
        }
      >
        <Form style={{ marginBottom: 10 }}>
          <Row>
            <Col span={6}>
              <Form.Item label="组件名称" {...formItemLayout}>
                {getFieldDecorator('componentName')(<Input />)}
              </Form.Item>
            </Col>
            <Col span={6}>
              <Form.Item label="组件编码" {...formItemLayout}>
                {getFieldDecorator('componentCode')(<Input />)}
              </Form.Item>
            </Col>
          </Row>
          <div style={{ textAlign: 'center' }}>
            <Button type="primary" className="margin-right" onClick={handleQuery}>
              查询
            </Button>
            <Button type="default" onClick={handleReset}>
              重置
            </Button>
          </div>
        </Form>
        <SlickTable
          rowKey={record => record.componentId}
          columns={columns}
          {...tableProps}
          rowClassName={record => {
            return record.componentId === props.selectComponent.componentId
              ? styles.clickRowStyle
              : '';
          }}
          onRow={record => {
            return {
              onClick: () => {
                saveSelectComponent(record);
              },
            };
          }}
        />
      </Card>
      {/* 新增/修改组件 */}
      {props.componentAddVisibleFlag ? (
        <ComponentAdd modalVisible={props.componentAddVisibleFlag} />
      ) : null}
    </div>
  );
}

export default connect(({ componentManage, setting }) => ({
  selectComponent: componentManage.selectComponent,
  componentAddVisibleFlag: componentManage.componentAddVisibleFlag,
  componentAddType: componentManage.componentAddType,
  size: setting.size,
}))(Form.create()(ComponentManage));
